﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using NewLife;
using Zdap.Common;

namespace Datav.Web.Api.Controllers
{
    /// <summary>
    /// 基类
    /// </summary>
    /// <remarks>
    ///
    /// </remarks>
    /// <param name="serviceFactory"></param>
    [Route("datavdesign/[controller]/[action]")]
    [ApiController]
    public class BaseController(IServiceFactory serviceFactory) : Controller
    {
        /// <summary>
        ///
        /// </summary>
        protected IServiceFactory _serviceFactory = serviceFactory;

        /// <summary>
        ///
        /// </summary>
        protected UserTicket CurrentUser { get; private set; }

        /// <summary>
        ///  Called before the action method is invoked.
        /// </summary>
        /// <param name="context"></param>
        [NonAction]
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ActionDescriptor is ControllerActionDescriptor descriptor)
            {
                if (descriptor.ControllerTypeInfo.IsDefined(typeof(AllowAnonymousAttribute), true)
                || descriptor.MethodInfo.IsDefined(typeof(AllowAnonymousAttribute), true))
                    return;
            }

            var r = UserTicketHelper.GetUserTicket(context.HttpContext);

            if (r.IsSuccess)
            {
                CurrentUser = r.Data;
            }
        }

        internal ResponseContext<T> ModelStateError<T>()
        {
            var result = new ResponseContext<T>();
            foreach (var item in ModelState.Values)
            {
                foreach (var error in item.Errors)
                {
                    result.Msg += error.ErrorMessage + "\r\n ";
                }
            }
            result.Msg = "入参格式问题，请详细阅读API Swagger 定义，字段的数据类型必须传正确。详细错误信息如下：" + result.Msg.TrimEnd("\r\n ");
            result.Code = CommonConstants.BadRequest;
            return result;
        }
    }
}